<?php

defined('_SECURITY_TOKEN') or die("caia fora");

class controlleruser //extends AppController
{

	function __construct(  )
	{
		
		$task	=	application::getTask();//( empty($_REQUEST['task'])? '':$_REQUEST['task']);
		
		switch( $task ){
			
			case 'create':
				
				
				try {
        						
								
					$parameters		=	application::getParameters();
								
					$email			=	$parameters->email;
					$password		=	$parameters->password;
					
					if(!empty($email)){
						//sem e-mail informado
						
						if(!empty($password)){
						//sem password informado
							
							if( !$this->existUser( $email ) ){
							
								if( $this->insertUser( $email, $password ) ){
									$result=array("status"=>1,
											"data"=>MSG_09_LOGIN_CRIADO_SUCESSO,
											"notification"=>9);
								}else{
									$result=array("status"=>0,
								"data"=>MSG_10_LOGIN_PROBLEMAS_AO_CRIAR_USUARIO,
								"notification"=>10);
								}
								
							}else{
								$result=array("status"=>0,
								"data"=>MSG_11_LOGIN_CRIAR_USUARIO_JA_EXISTE,
								"notification"=>11);
							}
					
						}else{
							//$result=array("status"=>"password Unknown");
							$result=array("status"=>0,
							"data"=>MSG_12_LOGIN_CRIAR_USUARIO_FALTA_PASSWORD,
							"notification"=>12);
						}
						
					}else{
						
						//$result=array("status"=>"e-mail Unknown");
						$result=array("status"=>0,
							"data"=>MSG_13_LOGIN_CRIAR_USUARIO_FALTA_EMAIL,
							"notification"=>13);
					}
					
					
	
					application::executeView( 'default', $result );
				
			    }
			    catch (AppException $e) {
			    	throw new AppException( $e->getMessage() );
			    }
			    //catch (Exception $e) {
			   //     echo "#Erro Fatal ('{$e->getMessage()}')\n{$e}\n";
			    //}
				
		
				
				
				break;
			case 'login':
				
				
				try {
        						
					//application::IsAuthenticationRequired(true);

					//echo ACCESS_RESTRICT.', <a href="index.php?component=login&controller=login&task=form&tmpl=default">clique aqui</a> para se autenticar.';
			
					$parameters		=	application::getParameters();
								
					$email			=	$parameters->email;
					$password		=	$parameters->password;
					
					
					if( application::getAuthentication() ){
						
						$result=array("status"=>1,
										"data"=>MSG_04_LOGIN_JA_LOGADO,
										"notification"=>4);
						
					}else{
											
						if( $this->existUser( $email ) ){
							
							$login = $this->login( $email, $password );
							
							if( $login ){
								
								$_SESSION['username']	=	$login[0]->email;
								$_SESSION['user_id']	=	$login[0]->id;
																						
								$result=array("status"=>1,
												"data"=>MSG_01_LOGIN_SUCESSO,
												"notification"=>1);
							}else{
								$result=array("status"=>0,
												"data"=>MSG_02_LOGIN_FALHA,
												"notification"=>2);
							}
							
						}else{
							$result=array("status"=>0,
											"data"=>MSG_03_LOGIN_NAO_EXISTE,
											"notification"=>3);
						}
		
					}
					
					application::executeView( 'default', $result );
				
			    }
			    catch (AppException $e) {
			    	throw new AppException( $e->getMessage() );
			    }
			    //catch (Exception $e) {
			    //    echo "#Erro Fatal ('{$e->getMessage()}')\n{$e}\n";
			   // }
				
		
				
				
				break;
			case 'status':
				
				
				
				try {
        						
					$e 	=	application::getParameters();
								
					//$_GET['notation']	=	$e[0]->job->authentication->notation;
					
					if( application::getAuthentication() ){
							
						$result=array("status"=>1,
										"data"=>MSG_05_LOGIN_STATUS_AUTENTICADO,
										"notification"=>5);						
						
					}else{
						$result=array("status"=>0,
										"data"=>MSG_06_LOGIN_NAO_AUTENTICADO,
										"notification"=>6);	
					}
	
					application::executeView( 'default', $result );
				
			    }
			    catch (AppException $e) {
			    	throw new AppException( $e->getMessage() );
			    	
			    }
			   // catch (Exception $e) {
			    //    echo "#Erro Fatal ('{$e->getMessage()}')\n{$e}\n";
			    //}
				
				//application::executeView( 'default', $result );
				
				
				break;
			case 'username':
				
				//
				try {
        						
					$e 					=	application::getParameters();
								
					//$_GET['notation']	=	$e[0]->job->authentication->notation;
					
					if( application::getAuthentication() ){
							
						$result=array("status"=>1,
									"data"=>application::getAuthenticationUserName(),
									"notification"=>5);						
						
					}else{
						//$result=array("username"=>"user not authenticated");
						$result=array("status"=>0,
									"data"=>MSG_06_LOGIN_NAO_AUTENTICADO,
									"notification"=>6);	
									
					}
	
					application::executeView( 'default', $result );
				
			    }
			    catch (AppException $e) {
			    	throw new AppException( $e->getMessage() );
					
			    }
			   // catch (Exception $e) {
			   //     echo "#Erro Fatal ('{$e->getMessage()}')\n{$e}\n";
			    //}
				
				
				break;	
			case 'newpassword':
				
				
				try {
					
					//application::IsAuthenticationRequired(true);
        						
					$parameters	=	application::getParameters();
					$email		=	$parameters->email;
					$password	=	$parameters->password;			

					
					if( application::getAuthentication() ){
						
						$this->newPassword($email, $password);
							
						$result=array("status"=>1,
									"data"=>MSG_07_LOGIN_PASSWORD_UPDATE,
									"notification"=>7);						
						
					}else{
						$result=array("status"=>0,
									"data"=>MSG_06_LOGIN_NAO_AUTENTICADO,
									"notification"=>6);	
					}
	
					application::executeView( 'default', $result );
				
			    }
			    catch (AppException $e) {
			    	throw new AppException( $e->getMessage() );
			    }
			    //catch (Exception $e) {
			    //    echo "#Erro Fatal ('{$e->getMessage()}')\n{$e}\n";
			   // }
				
		
				
				break;
			case 'logout':
				
				try{
					
					$this->logout( );
					
					$e 	=	application::getParameters();
									
					//$_GET['notation']	=	$e[0]->job->authentication->notation;
					
					if( application::getAuthentication() ){
							
						$result=array("status"=>1,
									"data"=>MSG_08_LOGIN_LOGOUT_SUCESSO,
									"notification"=>8);
					
					}else{
						
						$result=array("status"=>0,
										"data"=>MSG_06_LOGIN_NAO_AUTENTICADO,
										"notification"=>6);	
					
					}				
				
					application::executeView( 'default',$result );
					
				}
			    catch (AppException $e) {
			    	throw new AppException( $e->getMessage() );
			    }
				
				break;
				
			default:
				
				//echo "view não definida.";
				throw new AppException( MSG_23_METODO_NAO_DEFINIDO );
				
				break;
		}
		
	}
	
	
	
	public function newPassword( $email, $password ){
				
		$result=false;
				
		try {
			
			$model	=	application::getModel('user');
			
			$result	=	$model->newPassword( $email, $password );
			

	    }
	    catch (AppException $e) {
	    	throw new AppException( $e->getMessage() );
	    }
	
		return $result;
		
	}
	
	
	public function insertUser( $email, $password ){
				
		$result=false;
				
		try {
			
			$model	=	application::getModel('user');
			
			$result	=	$model->insertUser( $email, $password );
		
	    }
	    catch (AppException $e) {
	    	throw new AppException( $e->getMessage() );
	    }
	
		return $result;
		
	}


	public function existUser( $email ){
				
		$result=false;
		
		try{
			

			$model	=	application::getModel('user');
			
			$result	=	$model->existUser( $email );
		
		
		}catch (AppException $e) {
	    	throw new AppException( $e->getMessage() );
	    }
		
		return $result;
		
	}
	
	
	public function login( $email, $password ){
				
		$result=false;
		
		try {
			
			$model	=	application::getModel('user');
			
			$result	=	$model->login( $email,$password );
						
	    }
	    catch (AppException $e) {
	    	throw new AppException( $e->getMessage() );
	    }
		
		return $result;
		
	}
	
	public function getSchemaTable( $query ){
				
		$result=false;
				
		//$model	=	application::getModel('user');
		try{
			 
			$db = application::getDb( $args->type);
			
			$db->setParameters($args->hostname, $args->port, 
									$args->username, $args->password,
									$args->databasename);
			
			$query=	"select " 
	                	."ic.column_name, "
	                        ."CASE WHEN ic.character_maximum_length IS NULL THEN 0 ELSE ic.character_maximum_length END,"
	                        ."pd.description,"
	                        ."ic.udt_name"
	                       . " "
	                        ."from INFORMATION_SCHEMA.COLUMNS ic"
	                        .""
	                        ." inner join pg_class pc ON pc.relname=ic.table_name"
	                       . ""
	                        ." left join pg_description pd ON pd.objoid = pc.oid"
	                       . ""
	                       . " where"
	                        .""
	                       . " ic.table_name = '"+$query_table+"'"
	                       . " "
	                        ." order by ic.ordinal_position asc";
			
		//$result = $db->getQuery($query);
		}catch (AppException $e) {
	    	throw new AppException( $e->getMessage() );
	    }
		
		return $result;
		
	}
	
	
	public function getTableFromInQuery( $query ){
				
		$result=false;
		
		try{
					
			$query=	substr($query, 0, strpos("FROM", $query));
		
		}catch (AppException $e) {
	    	throw new AppException( $e->getMessage() );
	    }
		
		return $result;
		
	}

	/*
	public function authentication( $email, $password ){
			
		try{ 
				
			$model	=	application::getModel('user');
			
			$result	=	$model->authentication( $email, $password );
			
			if( $result )
				$result=1;//application::setAttribute('save', '1');
			else
				$result=2;//application::setAttribute('save', '2');
		
		}catch (AppException $e) {
	    	throw new AppException( $e->getMessage() );
	    }
		
		return $result;	
		
	}*/
	
	public function logout( ){
			
		try{
			application::session_logout();
			
		}catch (AppException $e) {
	    	throw new AppException( $e->getMessage() );
	    }
				

	}
	
	
}